//
//  MyCameraExpandableButton.m
//  OntheRoadV4
//
//  Created by ZhangYanhua on 14/12/4.
//  Copyright (c) 2014年 EricHuang. All rights reserved.
//

#import "MyCameraExpandableButton.h"

#define DEFAULT_CAMERA_YELLOW_COLOR   [UIColor colorWithRed:255.0f/255.0f green:204.0f/255.0f blue:4.0f/255.0f alpha:1.0f]

@implementation MyCameraExpandableButton

- (id)initWithFrame:(CGRect)frame
{
	self = [super initWithFrame:frame];
	if (self)
	{
		// Flash Button like parameters
		expanded = NO;
		maxHeight = 0;
		useAnimation = YES;
		borderWidth = 0.0f;
		innerBorderWidth = 0.0f;
		horizontalPadding = 18.0f;
//		verticalPadding = DEFAULT_VERT_PADDING;
//		timeout = DEFAULT_TIMEOUT;
//
//		[self addTarget:self action:@selector(chooseLabel:forEvent:) forControlEvents:UIControlEventTouchUpInside];
		
		self.borderColor = [UIColor clearColor];
		self.textColor = [UIColor whiteColor];
//		self.labelFont = DEFAULT_FONT;
//		self.unSelectedLabelFont = DEFAULT_UNSELECTED_FONT;
		
		self.backgroundColor = [UIColor clearColor];
		self.alpha = 1.0f;
		self.opaque = YES;
	}
	return self;
}

- (void)updateDisplay
{
	// maxHeight update
	maxWidth = 0;
	maxHeight = (leftTitleView != nil)?[leftTitleView defaultFrameSize].height + verticalPadding * 2.0f:0;
	for (DDView *v in labels)
	{
		maxHeight = MAX(maxHeight, [v defaultFrameSize].height + verticalPadding * 2.0f);
		maxWidth = MAX(maxWidth, [v defaultFrameSize].width);
	}
	
	// borderWidth update
	for (DDView *v in labels)
	{
		v.layer.borderWidth = innerBorderWidth;
	}
	
	cornerAdditionalPadding = 10.0f;
    
	leftWidth = cornerAdditionalPadding;
	if (leftTitleView != nil) leftWidth += 4.0f + [leftTitleView defaultFrameSize].width;
	
	self.layer.borderWidth  = borderWidth;
	self.layer.borderColor  = borderColor.CGColor;
	self.layer.cornerRadius = maxHeight/2.0f;
	
	[self setSelectedItem:0 animated:NO];
    for (int i = 0; i < labels.count; i++) {
        UIView *v = [labels objectAtIndex:i];
        if ([v isKindOfClass:[DDExpandableButtonCustomUILabel class]]) {
            UILabel *label = (UILabel *)v;
            if (i + 1 == labels.count) {
                label.textColor = [UIColor whiteColor];
            } else {
                label.textColor = DEFAULT_CAMERA_YELLOW_COLOR;
            }
        }
	}
}



- (void)setExpanded:(BOOL)_expanded animated:(BOOL)animated
{
    expanded = _expanded;

    if (animated)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.2f];
    }
    
    // set labels appearance
    
    if (expanded)
    {
        NSUInteger i = 0;
        CGFloat x = leftWidth;
        for (DDView *v in labels)
        {
            if (i != selectedItem)
            {
                if ([v isKindOfClass:[DDExpandableButtonCustomUILabel class]])
                {
                    [(DDExpandableButtonCustomUILabel *)v setFont:(unSelectedLabelFont != nil)?unSelectedLabelFont:labelFont];
                }
                if ([v respondsToSelector:@selector(setHighlighted:)])
                {
                    [v setHighlighted:NO];
                }
            }
            else if ([v respondsToSelector:@selector(setHighlighted:)])
            {
                [v setHighlighted:YES];
            }
            
            CGRect labelRect = CGRectMake(x, 0, [v defaultFrameSize].width + horizontalPadding * 2, maxHeight);
            x += labelRect.size.width - v.layer.borderWidth;
            v.frame = labelRect;
            
            if ((i > 0) && (i < ([labels count] - 1)) && (v.layer.borderWidth > 0))
            {
                v.layer.borderColor = borderColor.CGColor;
            }
            
            i++;
        }
        
        if (timeout > 0)
        {
            [self performSelector:@selector(shrinkButton) withObject:nil afterDelay:timeout];
        }
    }
    else
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(shrinkButton) object:nil];
        
        NSUInteger i = 0;
        CGFloat selectedWidth = 0;
        for (DDView *v in labels)
        {
            if ([v isKindOfClass:[DDExpandableButtonCustomUILabel class]])
            {
                [(DDExpandableButtonCustomUILabel *)v setFont:labelFont];
                [(DDExpandableButtonCustomUILabel *)v setTextColor:textColor];
            }
            if ([v respondsToSelector:@selector(setHighlighted:)])
            {
                [v setHighlighted:(i == selectedItem)];
            }
            
            CGRect r = CGRectZero;
            r.size.height = maxHeight;
            if (i < selectedItem)
            {
                r.origin.x = leftWidth;
            }
            else if (i == selectedItem)
            {
                r.size.width = [v defaultFrameSize].width + horizontalPadding * 2;
                r.origin.x = leftWidth;
                selectedWidth = r.size.width;
            }
            else if (i > selectedItem)
            {
                r.origin.x = leftWidth + selectedWidth;
            }
            v.layer.borderColor = [UIColor colorWithWhite:0.0f alpha:0.0f].CGColor;
            v.frame = r;
            
            i++;
        }
    }

    // set title frames
    leftTitleView.frame = CGRectMake(cornerAdditionalPadding, 0, [leftTitleView defaultFrameSize].width, maxHeight);
    
    for (int i = 0; i < labels.count; i++) {
        UIView *v = [labels objectAtIndex:i];
        if ([v isKindOfClass:[DDExpandableButtonCustomUILabel class]]) {
            UILabel *label = (UILabel *)v;
            if (i + 1 == labels.count) {
                label.textColor = [UIColor whiteColor];
            } else {
                label.textColor = DEFAULT_CAMERA_YELLOW_COLOR;
            }
        }
    }

    if (expanded) {
        if ([leftTitleView isKindOfClass:[DDExpandableButtonCustomUIImageView class]]) {
            UIImageView *leftImgView = (UIImageView *)leftTitleView;
            
            leftImgView.image = [self maskedImage:leftImgView.image
                                        WithColor:DEFAULT_CAMERA_YELLOW_COLOR];
        }
    } else {
        if ([leftTitleView isKindOfClass:[DDExpandableButtonCustomUIImageView class]]) {
            UIImageView *leftImgView = (UIImageView *)leftTitleView;
            
            if (selectedItem + 1 == labels.count) {
                leftImgView.image = [self maskedImage:leftImgView.image
                                            WithColor:[UIColor whiteColor]];
            } else {
                leftImgView.image = [self maskedImage:leftImgView.image
                                            WithColor:DEFAULT_CAMERA_YELLOW_COLOR];
            }
        }
    }

    // set whole frame
    [self setFrame:[self currentFrameRect]];
    
    if (animated)
    {
        [UIView commitAnimations];
    }
}

- (UIImage *)maskedImage:(UIImage *)image WithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0, 0, image.size.width, image.size.height);
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, image.scale);
    CGContextRef c = UIGraphicsGetCurrentContext();
    [image drawInRect:rect];
    CGContextSetFillColorWithColor(c, [color CGColor]);
    CGContextSetBlendMode(c, kCGBlendModeSourceAtop);
    CGContextFillRect(c, rect);
    UIImage *result = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return result;
}

- (void)setSelectedItem:(NSUInteger)selected animated:(BOOL)animated
{
    [super setSelectedItem:selected animated:animated];

    if ([leftTitleView isKindOfClass:[DDExpandableButtonCustomUIImageView class]]) {
        UIImageView *leftImgView = (UIImageView *)leftTitleView;

        if (selectedItem + 1 == labels.count) {
            leftImgView.image = [self maskedImage:leftImgView.image
                                        WithColor:[UIColor whiteColor]];
        } else {
            leftImgView.image = [self maskedImage:leftImgView.image
                                        WithColor:DEFAULT_CAMERA_YELLOW_COLOR];
        }
    }
}

- (DDView *)getViewFrom:(id)obj
{
	if ([obj isKindOfClass:[NSString class]])
	{
		DDExpandableButtonCustomUILabel *v = [[DDExpandableButtonCustomUILabel alloc] init];
		v.font = labelFont;
        v.textColor = textColor;
        v.backgroundColor = [UIColor clearColor];
		v.textAlignment = NSTextAlignmentLeft;
		v.opaque = YES;
		v.text = obj;
        v.clipsToBounds = YES;
		return v;
	}
	else if ([obj isKindOfClass:[UIImage class]])
	{
		DDExpandableButtonCustomUIImageView *v = [[DDExpandableButtonCustomUIImageView alloc] initWithImage:obj];
		v.backgroundColor = [UIColor clearColor];
		v.opaque = YES;
		v.contentMode = UIViewContentModeCenter;
		v.clipsToBounds = YES;
		return v;
	}
	else if (obj == nil)
	{
		return nil;
	}
	else
	{
//		NSAssert([obj isKindOfClass:[UIView class]], @"obj must be an UIView class !");
//		NSAssert([obj respondsToSelector:@selector(defaultFrameWidth)], @"obj must implement - (CGFloat)defaultFrameWidth !");
		return obj;
	}
}
@end
